import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
# from options.chrome_options import Options
from time import sleep
# from log.log import Logger
import openpyxl
from selenium.webdriver.support.wait import WebDriverWait
# #v1.0
# def open_browser(browser_type):
#     browser_type = browser_type.upper()
#     if browser_type is 'CHR':
#         driver = webdriver.Chrome()
#     elif browser_type is 'IE':
#         driver = webdriver.Ie()
#     elif browser_type is 'FF':
#         driver = webdriver.Firefox()
#     else:
#         driver = webdriver.Chrome()
#     return driver

#v2.0
def open_browser(browser_type):
    try:
        if browser_type == 'CHR':
            # Logger().log().info('正常启动浏览器中......')
            print('正在正常启动浏览器中...')
            driver = webdriver.Chrome(options=Options().options_conf())
        else:
            driver = getattr(webdriver, browser_type)()
    except Exception as e:
        # Logger().log().info("输入浏览器类型错误，默认调用谷歌浏览器，错误信息{}".format(e))
        driver = webdriver.Chrome()

    return driver

def load_workbook(workbook_path):
    return openpyxl.load_workbook(workbook_path)


class WebUIKeys:


    def __init__(self,browser_type):
        self.driver=open_browser(browser_type)
        # self.log = log
        # self.ccon = mysql.connector.connect(
        #     host='192.168.1.99',  # localhost
        #     user='root',  # root
        #     password='pass@word1',  # wxk111
        #     database='Admin019'  # first
        # )
        # print(self.ccon)
        # self.cmd = self.ccon.cursor()
        # # cmd.execute("show databases;")
        # # for x in cmd:
        # #     print(x)
        # # cmd.execute("{}".format(sql))
    def getUrl(self,url = None):
        print("打印驱动",self.driver)
        self.driver.get(url)
    def click(self,loc = None):
        ele = self.findEle(loc)
        ele.click()
    def input(self,loc=None, value=None):
        ele = self.findEle(loc)
        ele.send_keys(str(value))

    def sleep(self, value=None):
        self.driver.sleep(int(value))

    def intoIframe(self,loc):
        ele = self.findEle(loc)
        self.driver.switch_to_frame(ele)

    def allure_screenshot(self,expect,actual):
        try:
            assert expect == actual
        except AssertionError as e:
            # self.driver.save_screenshot()
            import allure
            screenshot = self.driver.get_screenshot_as_png()
            allure.attach(screenshot, "错误截图的名称", allure.attachment_type.PNG)
            raise e
    def findEle(self,loc = ''):
        ele = None
        self.ele = None
        if loc.startswith('xpath='):
            ele = self.driver.find_element_by_xpath(loc[loc.find('=')+1:])
        elif loc.startswith('id='):
            ele = self.driver.find_element_by_id(loc[loc.find('=')+1:])
        elif loc.startswith('name='):
            ele = self.driver.find_element_by_name(loc[loc.find('=')+1:])
        elif loc.startswith('tag_name='):
            ele = self.driver.find_element_by_tag_name(loc[loc.find('=')+1:])
        elif loc.startswith('link_text='):
            ele = self.driver.find_element_by_link_text(loc[loc.find('=')+1:])
        elif loc.startswith('partial_link_text='):
            ele = self.driver.find_element_by_partial_link_text(loc[loc.find('=')+1:])
        elif loc.startswith('css_seletor='):
            ele = self.driver.find_element_by_css_seletor(loc[loc.find('=')+1:])
        else:
            ele = self.driver.find_element_by_xpath(loc)
        self.ele = ele
        return ele

    def locator(self,type,value):
        # v1.0
        # if loc_type is 'xpath':
        #     return self.driver.find_element_by_xpath(value)
        # elif loc_type is 'id':
        #     return self.driver.find_element_by_id(value)
        try:
            return self.driver.find_element(getattr(By, type.upper()), value)
        except Exception as e:
            # Logger().log().info("定位元素出现异常，异常信息：\n{}".format(e))
            print(e)

    # def input(self, type, value, text):
    #     self.locator(type, value).send_keys(text)
    #
    # def click(self,type, value):
    #     self.locator(type, value).click()？
        #针对重复识别验证码
        # for i in range(1, 9):
        #     find_element(loc_type, loc_ex).click()
        #     try:
        #         sleep(5)
        #         find_element("xpath", '//*[text()="验证码错误"]')
        #     except:
        #         Logger().log().debug("输入验证码正确")
        #         break
        #     else:
        #         Logger().log().debug("验证码识别失败，第{}次重试".format(i))
        #         sleep(5)
        #         Logger().log().debug("清空验证码")
        #         find_element("xpath", '//*[@id="captcha_normal"]').clear()
        #         # 点击登录失败后自动刷新验证码，无需手动点击刷新
        #         # Logger().log().debug("点击更新验证码")
        #         # ActionChains(driver).move_to_element(find_element("id", "codeimage")).perform()
        #         # sleep(5)
        #         # find_element("id", "codeimage").click()
        #         # refresh_page()
        #         Logger().log().debug("识别验证码")
        #         iver = ivercode()
        #         Logger().log().debug("输入新的验证码")
        #         find_element("xpath", '//*[@id="captcha_normal"]').send_keys(iver)
        #         Logger().log().debug("点击登录")
        #         sleep(2)
        #         # find_element(loc_type, loc_ex).click()
        #         click(loc_type, loc_ex)
        #         sleep(2)

    def quit(self):
        self.driver.quit()

    def visit(self, text):
        self.driver.get(text)


    # def sleep(self,text):
    #     sleep(text)?

    def wait(self, text):
        self.driver.implicitly_wait(text)

    # 切换至新窗体
    def switch_to_new_current(self):
        handles = self.driver.window_handles
        self.driver.switch_to.window(handles[1])

    # 关闭旧窗体
    def close_old_current(self):
        self.driver.close()

    # 切换至旧窗体
    def switch_to_old_current(self):
        handles = self.driver.window_handles
        self.driver.switch_to.window(handles[0])

    # 切换至新窗体，并关闭旧窗体
    def switch_and_close(self):
        handles = self.driver.window_handles
        self.driver.close()
        self.driver.switch_to.window(handles[1])

    # 切换至Iframe窗体
    def switch_to_iframe(self, type, value):
        self.driver.switch_to.frame(self.locator(type, value))

    # 切换回默认窗体
    def switch_to_default(self):
        self.driver.switch_to.default_content()

    #文件上传
    def fileUp(self, text):
        import pywinauto
        from pywinauto.keyboard import send_keys
        app = pywinauto.Desktop()
        dlg = app["打开"]
        dlg.print_control_identifiers()
        dlg["Toolbar3"].click()
        send_keys(r"C:\Users\wxk\Desktop\不同大小的文件")
        send_keys("{VK_RETURN}")
        dlg["文件名(&N):Edit"].type_keys(text)#普通发票.jpg
        sleep(3)
        dlg["打开(&O)"].click()

    def ivercode(self):

        ele = self.driver.find_element_by_id("codeimage")
        ele.screenshot("../vercode_img/verify.png")
        headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
        data = {
            'user': 'wuqingfqng',
            'pass2': '6e8ebd2e301f3d5331e1e230ff3f3ca5',  # 密碼：wuqing&fqng
            "softid": "904357",
            "codetype": "1902"
        }
        userfile = open("../vercode_img/verify.png", "rb").read()
        userfile = {"userfile": ("../vercode_img/verify.png", userfile)}
        res = requests.post("http://upload.chaojiying.net/Upload/Processing.php", data=data, files=userfile,
                            headers=headers)
        res = res.json()
        vercode = res["pic_str"]
        vercode = vercode[:4]
        return vercode

    def assert_text(self, type, value, expect):
        try:
            reality = self.locator(type,value).text
            assert reality == expect
            # Logger().log().info("流程正确，断言成功！")
            print('断言成功')
            return True
        except Exception as e:
            # Logger().log().info("流程正确，断言失败！失败信息：{}".format(e))
            print('断言失败')
            return False
        # 滑动滚动条

    def slide(self):
        el = self.driver.find_element_by_xpath('//input[contains(text(), ’请选择账套’)]')
        js = 'argument[0].scrollIntoView()'
        self.driver.execute_script(js, el)
        # 缩放窗口

    def zoom_window(self):
        self.driver.set_window_size(500, 500)

        # 缩放页面

    def zoom_page(self):
        self.driver.execute_script("document.body.style.zoom='0.67'")

    def js_click(self, type,value):
        element = self.locator(type,value)
        self.driver.execute_script("arguments[0].click();", element)
    #滚动到指定元素
    def js_scroll(self, type,value):
        element = self.locator(type,value)
        self.driver.execute_script("argument[0],scrollIntoView();", element)

    def js_rmAttribute(self, type,value):
        element = self.locator(type,value)
        self.driver.execute_script("argument[0],removeAttribute('name');", element)#目前写死为移除name属性

    def get_sql_data(self, text):
        self.cmd.execute(text)
        res = self.cmd.fetchall()
        res = print(res)
        return res



    def js_assert_text(self, type,value,expect):
        try:
            element = WebDriverWait(self.driver, 10, 0.1).until(lambda el: self.locator(type,value), '元素定位失败')
            reality = self.driver.execute_script("return arguments[0].innerHTML;", element)
            assert reality == expect
            # Logger().log().info("流程正确，断言成功！")
            print('断言成功')
            return True
        except Exception as e:
            # Logger().log().info("流程正确，断言失败！失败信息：{}".format(e))
            print('断言失败')
            return False

    def mysql_assert_text(self, text, expect):
        try:
            sql = text
            # Logger().log().info("取到的sql语句：{}".format(sql))
            self.cmd.execute(sql)
            reality = self.cmd.fetchall()  # 当数据量大的时候会出现性能问题，所以建议使用for循环一行行读取数据
            # for i in range(1,self.cmd.rowcount):
            #     row = self.cmd.fetchone()
            #     if row[0][0] == kwargs['expect']:
            #         print("断言成功")
            #         break
            #     else:
            #         print("断言失败")
            reality = reality[0][0]
            reality = str(reality)
            # import re
            # reality = str(reality)
            # reality = re.findall('[\d\.\d]',reality)
            # return reality
            # Logger().log().info("返回的数据：{}".format(reality))
            assert reality == expect
            # Logger().log().info("流程正确，断言成功！")
            return True
        except Exception as e:
            # Logger().log().exception("流程正确，断言失败！失败信息：{}".format(e))
            return False

    #unittest断言函数
    def get_element(self,loc_type,value):
        return self.driver.find_element(getattr(By,loc_type.upper()),value).text
